﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace QA.TFS.Utils
{
    public class XMLLoadConfig
    {

        public static Dictionary<string, string> loadConfig(IXMLDefinition definition)
        {
            try
            {
                List<ConfigItem> lstItems = definition.GetElements();
                Dictionary<string, string> ctxUpdates = new Dictionary<string, string>();

                foreach (ConfigItem item in lstItems)
                    ctxUpdates[item.Name] = item.Value;

                return ctxUpdates;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static void loadConfig(WebTestContext context, IXMLDefinition definition, string contextParameter, string xmlParameter)
        {
            try
            {
                string element = definition.GetValue(xmlParameter) as string;
                if (!context.ContainsKey(contextParameter))
                    context.Add(contextParameter, element);
                else
                    context[contextParameter] = element;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static void loadConfig(WebTestContext context, IXMLDefinition definition)
        {
            try
            {
                List<ConfigItem> lstItems = definition.GetElements();
                Dictionary<string, string> ctxUpdates = new Dictionary<string, string>();
                foreach (ConfigItem configItem in lstItems)
                {
                    var results = from p in context
                                  where p.Key.Contains("." + configItem.Name)
                                  select p;

                    foreach (var item in results)
                        if (!item.Key.Contains("$") && !item.Key.Contains("HIDDEN") && !item.Key.Contains("#"))
                            if (!ctxUpdates.ContainsKey(item.Key))
                                ctxUpdates.Add(item.Key, configItem.Value);
                }

                foreach (KeyValuePair<string, string> item in ctxUpdates)
                    context[item.Key] = item.Value;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
